<!DOCTYPE html>
<html>
<head>
    <title>文章wangEditor编辑</title>
    {% include 'system/common/header.html' %}</head>
    <link rel="stylesheet" href="{{ url_for('admin.static', filename='system/component/wangeditor/style.css') }}"/>
    <style>

    </style>
<body>
<form class="layui-form" action="">
    <div class="mainBox">
        <div class="main-container">
            <div class="main-container">
                <div class="layui-form-item layui-hide">
                    <label class="layui-form-label">编号</label>
                    <div class="layui-input-block">
                        <input type="text" value="{{ post.id }}" name="postId" lay-verify="required"
                               autocomplete="off" placeholder="文章编号" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">文章标题</label>
                    <div class="layui-input-block">
                        <input type="text" value="{{ post.title or '' }}" name="title" lay-verify="required"
                               autocomplete="off" placeholder="文章标题" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">文章别名</label>
                    <div class="layui-input-block">
                        <input type="text" value="{{ post.slug or '' }}" name="slug" lay-verify="required"
                               autocomplete="off" placeholder="文章别名" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">分类目录</label>
                    <div class="layui-input-block">
                        <div class="layui-input-inline" style="width: 100%;">
                            <input type="text" id="category-display" placeholder="请选择分类" readonly class="layui-input" style="cursor: pointer;">
                            <input type="hidden" name="category_id" id="category-id" lay-verify="required">
                        </div>
                        <div id="category-tree" style="display: none; position: absolute; z-index: 1000; background: white; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 2px 8px rgba(0,0,0,0.15); max-height: 300px; overflow-y: auto; width: 100%;">
                            <div style="padding: 10px; border-bottom: 1px solid #e6e6e6;">
                                <input type="text" id="category-search" placeholder="搜索分类..." class="layui-input" style="height: 32px; font-size: 12px;">
                            </div>
                            <div id="category-tree-content"></div>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">标签</label>
                    <div class="layui-input-block">
                        <div id="tag-container" class="layui-form-mid">
                            <div class="layui-btn-group" id="selected-tags"></div>
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="add-tag-btn">
                                <i class="layui-icon layui-icon-add-1"></i> 添加标签
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">文章摘要</label>
                    <div class="layui-input-block">
                        <textarea placeholder="文章摘要" name="excerpt" class="layui-textarea">{{ post.excerpt or '' }}</textarea>
                    </div>
                </div>
                
                <!-- 特色图像 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">特色图像</label>
                    <div class="layui-input-block">
                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <input type="text" name="featured_image" id="featured-image-url" placeholder="请输入图片地址或上传图片" value="{{ post.featured_image or '' }}" class="layui-input">
                            </div>
                            <div class="layui-col-md6">
                                <button type="button" class="layui-btn layui-btn-primary" id="upload-featured-image">
                                    <i class="layui-icon layui-icon-upload"></i> 上传图片
                                </button>
                                <button type="button" class="layui-btn layui-btn-normal" id="paste-image-url">
                                    <i class="layui-icon layui-icon-link"></i> 粘贴地址
                                </button>
                            </div>
                        </div>
                        <div id="featured-image-preview" style="margin-top: 10px; display: none;">
                            <img id="preview-img" src="" alt="特色图像预览" style="max-width: 300px; max-height: 200px; border: 1px solid #e6e6e6; border-radius: 2px;">
                            <div style="margin-top: 5px;">
                                <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" id="remove-featured-image">
                                    <i class="layui-icon layui-icon-close"></i> 移除图片
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">文章内容</label>
                    <div id="editor-wrapper">
                      <div id="toolbar-container"><!-- 工具栏 --></div>
                      <div id="editor-container"><!-- 编辑器 --></div>
                      <textarea name="content" id="editor-content" style="display: none;"></textarea>
                    </div>
                </div>
                
                <!-- SEO信息 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_title" placeholder="SEO标题（可选）" value="{{ post.meta_title or '' }}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO关键词</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_keywords" placeholder="SEO关键词，多个关键词用逗号分隔（可选）" value="{{ post.meta_keywords or '' }}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">SEO描述</label>
                    <div class="layui-input-block">
                        <textarea name="meta_description" placeholder="SEO描述（可选）" class="layui-textarea" style="height: 80px;">{{ post.meta_description or '' }}</textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-sm" lay-submit=""
                    lay-filter="post-update">
                <i class="layui-icon layui-icon-ok"></i>
                草稿
            </button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="publish-btn">
                <i class="layui-icon layui-icon-release"></i>
                发布
            </button>
        </div>
    </div>
</form>
{% include 'system/common/footer.html' %}
<style>
#editor-wrapper {
    border: 1px solid #ccc;
    z-index: 100; /* 按需定义 */
}
#toolbar-container {
    border-bottom: 1px solid #ccc;
}
#editor-container {
    height: 500px;
}
</style>

<!-- 全局变量 -->
<script>
let selectedTags = [];
let allTags = [];
let editor = null; // 全局编辑器实例
</script>
<script src="{{ url_for('admin.static', filename='system/component/wangeditor/index.js') }}"></script>
<script>
// 初始化wangEditor
document.addEventListener('DOMContentLoaded', function() {
    console.log('开始初始化wangEditor...');
    
    // 检查wangEditor是否加载
    if (typeof window.wangEditor === 'undefined') {
        console.error('wangEditor未加载');
        return;
    }
    
    const { createEditor, createToolbar } = window.wangEditor;
    
    if (!createEditor || !createToolbar) {
        console.error('wangEditor API未正确加载');
        return;
    }
    
    console.log('wangEditor API加载成功');
    
    // 获取文章内容
    const postId = "{{ post.id }}";
    console.log('获取文章ID:', postId);
    
    // 通过AJAX获取文章内容
    fetch(`/admin/cms/post/content/${postId}`)
        .then(response => {
            console.log('AJAX响应状态:', response.status);
            return response.json();
        })
        .then(data => {
            console.log('AJAX响应数据:', data);
            let postContent = '';
            if (data.success) {
                postContent = data.data.content || '';
                console.log('获取到文章内容:', postContent);
            } else {
                console.warn('获取文章内容失败:', data.msg);
                postContent = '';
            }
            
            // 初始化编辑器
            initEditor(postContent);
        })
        .catch(error => {
            console.error('获取文章内容出错:', error);
            initEditor('');
        });
    
    // 初始化编辑器函数
    function initEditor(content) {
        console.log('初始化编辑器，内容:', content);
        
        // 编辑器配置
        const editorConfig = {
            placeholder: '请输入文章内容...',
            onChange(editor) {
                const html = editor.getHtml();
                console.log('编辑器内容变化:', html);
                // 同步到隐藏的textarea
                document.getElementById('editor-content').value = html;
            },
            // 图片上传配置
            MENU_CONF: {
                            uploadImage: {
                server: '/admin/cms/post/upload',
                fieldName: 'image',
                maxFileSize: 10 * 1024 * 1024, // 10MB
                maxNumberOfFiles: 10,
                allowedFileTypes: ['image/*'],
                meta: {
                    type: 'images'
                },
                metaWithUrl: true,
                withCredentials: false,
                timeout: 5 * 1000, // 5s
                // 自定义响应处理
                customInsert(res, insertFn) {
                    console.log('自定义插入图片:', res);
                    if (res.errorCode === 0) {
                        insertFn(res.data.src, res.data.alt, res.data.src);
                    }
                },
                    onBeforeUpload(file) {
                        console.log('图片上传开始:', file.name);
                        return file;
                    },
                    onProgress(progress) {
                        console.log('图片上传进度:', progress);
                    },
                                    onSuccess(file, res) {
                    console.log('图片上传成功:', res);
                    if (res.errorCode === 0) {
                        // 返回图片URL，wangEditor会自动插入
                        console.log('返回图片URL:', res.data.src);
                        // 返回完整的响应数据，让wangEditor自己处理
                        return res;
                    } else {
                        console.error('图片上传失败:', res);
                        return false;
                    }
                },
                    onFailed(file, res) {
                        console.error('图片上传失败:', res);
                        layer.msg('图片上传失败: ' + (res.msg || '未知错误'), {icon: 2});
                    },
                    onError(file, err, res) {
                        console.error('图片上传错误:', err);
                        layer.msg('图片上传错误: ' + err.message, {icon: 2});
                    }
                },
                            uploadVideo: {
                server: '/admin/cms/post/upload',
                fieldName: 'video',
                maxFileSize: 500 * 1024 * 1024, // 500MB，与服务器配置一致
                maxNumberOfFiles: 5,
                allowedFileTypes: ['video/*'],
                meta: {
                    type: 'video'
                },
                metaWithUrl: true,
                withCredentials: false,
                timeout: 60 * 1000, // 60s
                // 自定义响应处理
                customInsert(res, insertFn) {
                    console.log('自定义插入视频:', res);
                    if (res.errorCode === 0) {
                        insertFn(res.data.src, res.data.alt, res.data.src);
                    }
                },
                    onBeforeUpload(file) {
                        console.log('视频上传开始:', file.name);
                        return file;
                    },
                    onProgress(progress) {
                        console.log('视频上传进度:', progress);
                    },
                                    onSuccess(file, res) {
                    console.log('视频上传成功:', res);
                    if (res.errorCode === 0) {
                        // 返回视频URL，wangEditor会自动插入
                        console.log('返回视频URL:', res.data.src);
                        // 返回完整的响应数据，让wangEditor自己处理
                        return res;
                    } else {
                        console.error('视频上传失败:', res);
                        return false;
                    }
                },
                    onFailed(file, res) {
                        console.error('视频上传失败:', res);
                        layer.msg('视频上传失败: ' + (res.msg || '未知错误'), {icon: 2});
                    },
                    onError(file, err, res) {
                        console.error('视频上传错误:', err);
                        layer.msg('视频上传错误: ' + err.message, {icon: 2});
                                    },
                insertImage: {
                    checkImage: true,
                    parseImageSrc: (src) => {
                        console.log('解析图片链接:', src);
                        return src;
                    },
                    onInsertedImage: (imageNode) => {
                        console.log('图片插入成功:', imageNode);
                    }
                },
                insertVideo: {
                    checkVideo: true,
                    parseVideoSrc: (src) => {
                        console.log('解析视频链接:', src);
                        return src;
                    },
                    onInsertedVideo: (videoNode) => {
                        console.log('视频插入成功:', videoNode);
                    }
                }
            }
        }
    };
        
        // 创建编辑器
        try {
            editor = createEditor({
                selector: '#editor-container',
                html: content || '<p><br></p>',
                config: editorConfig,
                mode: 'default',
            });
            
            console.log('编辑器创建成功:', editor);
            
            // 创建工具栏
            const toolbarConfig = {
                toolbarKeys: [
                    'headerSelect',
                    'bold',
                    'italic',
                    'underline',
                    'through',
                    '|',
                    'color',
                    'bgColor',
                    '|',
                    'fontSize',
                    'fontFamily',
                    'lineHeight',
                    '|',
                    'bulletedList',
                    'numberedList',
                    'todo',
                    '|',
                    'justifyLeft',
                    'justifyRight',
                    'justifyCenter',
                    'justifyJustify',
                    '|',
                    'emotion',
                    'insertLink',
                    'uploadImage',
                    'insertImage',  // 通过链接插入图片
                    'uploadVideo',
                    'insertVideo',  // 通过链接插入视频
                    'insertTable',
                    'codeBlock',
                    'divider',
                    '|',
                    'undo',
                    'redo',
                    '|',
                    'fullScreen'
                ]
            };
            const toolbar = createToolbar({
                editor,
                selector: '#toolbar-container',
                config: toolbarConfig,
                mode: 'default',
            });
            
            console.log('工具栏创建成功:', toolbar);
            
            // 将编辑器实例设为全局变量
            window.editor = editor;
            
            // 添加测试上传功能的按钮
            const testButton = document.createElement('button');
            testButton.textContent = '测试上传功能';
            testButton.style.cssText = 'position: fixed; top: 10px; right: 10px; z-index: 9999; padding: 10px; background: #007cba; color: white; border: none; border-radius: 4px; cursor: pointer;';
            testButton.onclick = function() {
                console.log('测试上传功能');
                console.log('编辑器实例:', editor);
                console.log('编辑器配置:', editorConfig);
                layer.msg('上传功能已配置，请尝试在编辑器中上传图片或视频', {icon: 1});
            };
            document.body.appendChild(testButton);
            
        } catch (error) {
            console.error('编辑器初始化失败:', error);
        }
    }
});

// 获取编辑器内容的函数
function getEditorContent() {
    let content = '';
    
    // 方法1: 使用编辑器API
    if (editor && typeof editor.getHtml === 'function') {
        content = editor.getHtml();
        console.log('从编辑器API获取内容:', content);
        return content;
    }
    
    // 方法2: 从隐藏的textarea获取
    const textarea = document.getElementById('editor-content');
    if (textarea && textarea.value) {
        content = textarea.value;
        console.log('从textarea获取内容:', content);
        return content;
    }
    
    // 方法3: 从DOM获取
    const editorElement = document.querySelector('#editor-container');
    if (editorElement) {
        const contentElement = editorElement.querySelector('[contenteditable="true"]') ||
                              editorElement.querySelector('.w-e-text') ||
                              editorElement;
        
        if (contentElement) {
            content = contentElement.innerHTML;
            console.log('从DOM获取内容:', content);
            return content;
        }
    }
    
    console.warn('无法获取编辑器内容');
    return '';
}

// 加载分类数据
function loadCategories() {
    layui.use(['jquery', 'tree'], function() {
        let $ = layui.jquery;
        let tree = layui.tree;
        $.ajax({
            url: '/admin/cms/post/categories',
            type: 'GET',
            success: function(result) {
                if (result.success) {
                    console.log('分类数据:', result.data);
                    
                    // 转换数据格式为树形组件需要的格式
                    function convertToTreeData(categories) {
                        return categories.map(function(category) {
                            return {
                                id: category.id,
                                title: category.title,
                                children: category.children && category.children.length > 0 ? convertToTreeData(category.children) : []
                            };
                        });
                    }
                    
                    const treeData = convertToTreeData(result.data);
                    console.log('树形数据:', treeData);
                    
                    // 渲染树形组件
                    tree.render({
                        elem: '#category-tree-content',
                        data: treeData,
                        showLine: true,
                        click: function(obj) {
                            console.log('选择分类:', obj.data);
                            $('#category-display').val(obj.data.title);
                            $('#category-id').val(obj.data.id);
                            $('#category-tree').hide();
                        }
                    });
                    
                    // 绑定点击事件
                    $('#category-display').click(function() {
                        $('#category-tree').toggle();
                        if ($('#category-tree').is(':visible')) {
                            $('#category-search').focus();
                        }
                    });
                    
                    // 点击其他地方隐藏树形组件
                    $(document).click(function(e) {
                        if (!$(e.target).closest('#category-display, #category-tree').length) {
                            $('#category-tree').hide();
                        }
                    });
                    
                    // 搜索功能
                    $('#category-search').on('input', function() {
                        const searchText = $(this).val().toLowerCase().trim();
                        console.log('搜索文本:', searchText);
                        
                        if (!searchText) {
                            // 如果搜索框为空，显示所有分类
                            tree.render({
                                elem: '#category-tree-content',
                                data: treeData,
                                showLine: true,
                                click: function(obj) {
                                    console.log('选择分类:', obj.data);
                                    $('#category-display').val(obj.data.title);
                                    $('#category-id').val(obj.data.id);
                                    $('#category-tree').hide();
                                }
                            });
                            return;
                        }
                        
                        // 搜索匹配的分类
                        function searchCategories(categories, searchText) {
                            let results = [];
                            
                            for (let category of categories) {
                                // 检查当前分类是否匹配
                                if (category.title.toLowerCase().includes(searchText)) {
                                    results.push({
                                        id: category.id,
                                        title: category.title,
                                        children: []
                                    });
                                }
                                
                                // 递归搜索子分类
                                if (category.children && category.children.length > 0) {
                                    const childResults = searchCategories(category.children, searchText);
                                    results = results.concat(childResults);
                                }
                            }
                            
                            return results;
                        }
                        
                        const searchResults = searchCategories(treeData, searchText);
                        console.log('搜索结果:', searchResults);
                        
                        // 渲染搜索结果
                        if (searchResults.length > 0) {
                            tree.render({
                                elem: '#category-tree-content',
                                data: searchResults,
                                showLine: true,
                                click: function(obj) {
                                    console.log('选择分类:', obj.data);
                                    $('#category-display').val(obj.data.title);
                                    $('#category-id').val(obj.data.id);
                                    $('#category-tree').hide();
                                }
                            });
                        } else {
                            // 没有搜索结果
                            $('#category-tree-content').html('<div style="padding: 20px; text-align: center; color: #999;">没有找到匹配的分类</div>');
                        }
                    });
                    
                    // 搜索框回车键处理
                    $('#category-search').on('keydown', function(e) {
                        if (e.keyCode === 13) { // Enter键
                            e.preventDefault();
                            const firstResult = $('#category-tree-content .layui-tree-txt').first();
                            if (firstResult.length > 0) {
                                firstResult.click();
                            }
                        }
                    });
                    
                    // 设置当前选中的分类
                    const currentCategoryId = "{{ post.category_id }}";
                    if (currentCategoryId) {
                        // 查找当前分类的标题
                        function findCategoryTitle(categories, targetId) {
                            for (let category of categories) {
                                if (category.id == targetId) {
                                    return category.title;
                                }
                                if (category.children && category.children.length > 0) {
                                    const title = findCategoryTitle(category.children, targetId);
                                    if (title) return title;
                                }
                            }
                            return null;
                        }
                        
                        const categoryTitle = findCategoryTitle(result.data, currentCategoryId);
                        if (categoryTitle) {
                            $('#category-display').val(categoryTitle);
                            $('#category-id').val(currentCategoryId);
                        }
                    }
                }
            },
            error: function() {
                layer.msg('加载分类失败', {icon: 2});
            }
        });
    });
}

// 加载标签数据
function loadTags() {
    layui.use(['jquery'], function() {
        let $ = layui.jquery;
        $.ajax({
            url: '/admin/cms/post/tags',
            type: 'GET',
            success: function(result) {
                if (result.success) {
                    allTags = result.data;
                    // 加载文章的标签
                    loadPostTags();
                }
            },
            error: function() {
                layer.msg('加载标签失败', {icon: 2});
            }
        });
    });
}

// 加载文章的标签
function loadPostTags() {
    layui.use(['jquery'], function() {
        let $ = layui.jquery;
        const postId = "{{ post.id }}";
        $.ajax({
            url: `/admin/cms/post/post-tags/${postId}`,
            type: 'GET',
            success: function(result) {
                if (result.success) {
                    selectedTags = result.data;
                    renderSelectedTags();
                }
            },
            error: function() {
                console.log('文章没有标签或加载失败');
            }
        });
    });
}

// 显示标签选择弹窗
function showTagSelector() {
    layui.use(['jquery', 'layer', 'form'], function() {
        let $ = layui.jquery;
        let layer = layui.layer;
        let form = layui.form;
        
        let tagHtml = '<div style="padding: 20px;">';
        tagHtml += '<div class="layui-form-item">';
        tagHtml += '<label class="layui-form-label">搜索标签</label>';
        tagHtml += '<div class="layui-input-block">';
        tagHtml += '<input type="text" id="tag-search" placeholder="输入标签名称搜索" class="layui-input">';
        tagHtml += '</div>';
        tagHtml += '</div>';
        tagHtml += '<div id="tag-list" style="max-height: 300px; overflow-y: auto;">';
        
        allTags.forEach(function(tag) {
            const isSelected = selectedTags.some(t => t.id === tag.id);
            tagHtml += `<div class="layui-form-item">`;
            tagHtml += `<input type="checkbox" name="tag_${tag.id}" value="${tag.id}" title="${tag.title || tag.name || '未命名标签'}" ${isSelected ? 'checked' : ''}>`;
            tagHtml += `<label style="margin-left: 10px;">${tag.title || tag.name || '未命名标签'}</label>`;
            tagHtml += `</div>`;
        });
        
        tagHtml += '</div></div>';
        
        layer.open({
            type: 1,
            title: '选择标签',
            content: tagHtml,
            area: ['500px', '400px'],
            btn: ['确定', '取消'],
            yes: function(index) {
                // 获取选中的标签
                const checkedTags = [];
                allTags.forEach(function(tag) {
                    if ($(`input[name="tag_${tag.id}"]`).is(':checked')) {
                        checkedTags.push(tag);
                    }
                });
                
                selectedTags = checkedTags;
                renderSelectedTags();
                layer.close(index);
            }
        });
        
        // 绑定搜索功能
        $('#tag-search').on('input', function() {
            const searchText = $(this).val().toLowerCase();
            allTags.forEach(function(tag) {
                const checkbox = $(`input[name="tag_${tag.id}"]`);
                const item = checkbox.closest('.layui-form-item');
                if (tag.title.toLowerCase().includes(searchText)) {
                    item.show();
                } else {
                    item.hide();
                }
            });
        });
        
        form.render('checkbox');
    });
}

// 渲染已选择的标签
function renderSelectedTags() {
    layui.use(['jquery'], function() {
        let $ = layui.jquery;
        const container = $('#selected-tags');
        container.empty();
        
        if (selectedTags && selectedTags.length > 0) {
            selectedTags.forEach(function(tag) {
                container.append(`
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" data-tag-id="${tag.id}">
                        ${tag.title || tag.name || '未命名标签'}
                        <i class="layui-icon layui-icon-close" onclick="removeTag(${tag.id})"></i>
                    </button>
                `);
            });
        } else {
            container.append('<span class="layui-text layui-text-color">暂无标签</span>');
        }
    });
}

// 移除标签
function removeTag(tagId) {
    selectedTags = selectedTags.filter(tag => tag.id !== tagId);
    renderSelectedTags();
}

// 绑定事件
layui.use(['form', 'jquery'], function() {
    let $ = layui.jquery;
    
    // 加载数据
    loadCategories();
    loadTags();
    
    // 绑定添加标签按钮
    $('#add-tag-btn').click(function() {
        showTagSelector();
    });
});
</script>

<script>
    layui.use(['form', 'jquery'], function () {
        let form = layui.form
        let $ = layui.jquery
        
        console.log('Layui form 初始化完成');

        // 特色图像功能
        // 上传图片
        $('#upload-featured-image').click(function() {
            // 创建一个隐藏的文件输入框
            let fileInput = $('<input type="file" accept="image/*" style="display: none;">');
            $('body').append(fileInput);
            
            fileInput.click();
            
            fileInput.on('change', function() {
                let file = this.files[0];
                if (file) {
                    // 创建FormData对象
                    let formData = new FormData();
                    formData.append('image', file);
                    formData.append('type', 'images');
                    
                    // 上传文件
                    $.ajax({
                        url: '/admin/cms/post/upload',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(result) {
                            if (result.errorCode === 0) {
                                let imageUrl = result.data.src;
                                $('#featured-image-url').val(imageUrl);
                                showImagePreview(imageUrl);
                                layer.msg('图片上传成功', {icon: 1});
                            } else {
                                layer.msg(result.msg || '上传失败', {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('上传失败', {icon: 2});
                        }
                    });
                }
                
                // 移除临时文件输入框
                fileInput.remove();
            });
        });
        
        // 粘贴图片地址
        $('#paste-image-url').click(function() {
            layer.prompt({
                title: '请输入图片地址',
                formType: 0,
                value: '',
                area: ['400px', '150px']
            }, function(value, index) {
                if (value && value.trim()) {
                    $('#featured-image-url').val(value.trim());
                    showImagePreview(value.trim());
                    layer.close(index);
                    layer.msg('图片地址已设置', {icon: 1});
                } else {
                    layer.msg('请输入有效的图片地址', {icon: 2});
                }
            });
        });
        
        // 移除特色图像
        $('#remove-featured-image').click(function() {
            $('#featured-image-url').val('');
            $('#featured-image-preview').hide();
            layer.msg('特色图像已移除', {icon: 1});
        });
        
        // 显示图片预览
        function showImagePreview(imageUrl) {
            if (imageUrl && imageUrl.trim()) {
                $('#preview-img').attr('src', imageUrl);
                $('#featured-image-preview').show();
            } else {
                $('#featured-image-preview').hide();
            }
        }
        
        // 监听图片地址输入框变化
        $('#featured-image-url').on('input', function() {
            let imageUrl = $(this).val().trim();
            showImagePreview(imageUrl);
        });
        
        // 初始化特色图像预览（如果有值）
        let initialImageUrl = $('#featured-image-url').val();
        if (initialImageUrl) {
            showImagePreview(initialImageUrl);
        }

        // 草稿按钮事件处理
        form.on('submit(post-update)', function (data) {
            console.log('草稿按钮事件触发', data);
            
            // 获取编辑器内容
            let editorContent = getEditorContent();
            
            // 构建提交数据
            let submitData = {
                id: data.field.postId,
                title: data.field.title,
                slug: data.field.slug,
                excerpt: data.field.excerpt,
                featured_image: data.field.featured_image || '',
                content: editorContent,
                category_id: data.field.category_id ? parseInt(data.field.category_id) : null,
                tag_ids: selectedTags.map(tag => tag.id),
                meta_title: data.field.meta_title || '',
                meta_keywords: data.field.meta_keywords || '',
                meta_description: data.field.meta_description || '',
                type: 'wangEditor',
                status: 'draft'  // 保存为草稿
            }
            
            console.log('准备提交的数据:', submitData);
            console.log('提交URL:', '/admin/cms/post/update/' + data.field.postId);
            
            $.ajax({
                url: '/admin/cms/post/update/' + data.field.postId,
                data: JSON.stringify(submitData),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    console.log('请求成功:', result);
                    if (result.success) {
                        layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
                            parent.layui.table.reload('post-table')
                        })
                    } else {
                        layer.msg(result.msg, { icon: 2, time: 1000 })
                    }
                },
                error: function (xhr, status, error) {
                    console.error('请求失败:', xhr, status, error);
                    layer.msg('保存失败: ' + error, { icon: 2, time: 2000 })
                }
            })
            return false
        })
        
        // 发布按钮事件处理
        $('#publish-btn').click(function() {
            console.log('发布按钮事件触发');
            
            // 获取表单数据 - 使用与草稿按钮相同的方式
            let formData = {};
            $('form.layui-form input, form.layui-form textarea, form.layui-form select').each(function() {
                let name = $(this).attr('name');
                let value = $(this).val();
                if (name) {
                    formData[name] = value;
                }
            });
            
            console.log('获取到的表单数据:', formData);
            
            // 获取编辑器内容
            let editorContent = getEditorContent();
            
            // 构建提交数据
            let submitData = {
                id: formData.postId,
                title: formData.title,
                slug: formData.slug,
                excerpt: formData.excerpt,
                featured_image: formData.featured_image || '',
                content: editorContent,
                category_id: formData.category_id ? parseInt(formData.category_id) : null,
                tag_ids: selectedTags.map(tag => tag.id),
                meta_title: formData.meta_title || '',
                meta_keywords: formData.meta_keywords || '',
                meta_description: formData.meta_description || '',
                type: 'wangEditor',
                status: 'published'  // 发布状态
            }
            
            console.log('准备发布的数据:', submitData);
            console.log('发布URL:', '/admin/cms/post/update/' + formData.postId);
            
            $.ajax({
                url: '/admin/cms/post/update/' + formData.postId,
                data: JSON.stringify(submitData),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    console.log('请求成功:', result);
                    if (result.success) {
                        layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
                            parent.layui.table.reload('post-table')
                        })
                    } else {
                        layer.msg(result.msg, { icon: 2, time: 1000 })
                    }
                },
                error: function (xhr, status, error) {
                    console.error('请求失败:', xhr, status, error);
                    layer.msg('发布失败: ' + error, { icon: 2, time: 2000 })
                }
            })
        })
    })
</script>

</body>
</html>